package com.inossem.warehousestorage_inossem.activity.out_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.inossem.loadandrefresh.PullToRefreshLayout;
import com.inossem.loadandrefresh.pullableview.PullableListView;
import com.inossem.utils.base.ArithUtils;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.allocation.out_storage.extra.AllocationOutStorageExtra;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.change_storage.extra.ChangeStorageExtra;
import com.inossem.warehousestorage_inossem.activity.out_storage.extra.OutStorageExtra;
import com.inossem.warehousestorage_inossem.adapter.outStorage.OutStorageDetailBatchListAdapter;
import com.inossem.warehousestorage_inossem.bean.changeStorage.chuangyou.CYChangeStorageGetBatchRequestBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.BatchBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.ItemListBean;
import com.inossem.warehousestorage_inossem.constant.TypeEnum;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.listener.OutStorageDetailBatchListener;
import com.inossem.warehousestorage_inossem.request.allocation.AllocationAllBatchRequest;
import com.inossem.warehousestorage_inossem.request.changeStorage.chuangyou.CYChangeStorageMaterialBatchRequest;
import com.inossem.warehousestorage_inossem.request.outStorage.AddBatchRequest;
import com.inossem.warehousestorage_inossem.request.outStorage.GetDefaultBatchRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.CYChangeStorageUtils;
import com.inossem.warehousestorage_inossem.utils.OutStorageUtils;

import java.util.ArrayList;
import java.util.List;


//按批次出库
public class OutStorageDetailBatchActivity extends BaseActivity {

    private TextView title;

    private PullToRefreshLayout refresh;

    private PullableListView pickingOutStorageDetailList;

    private OutStorageDetailBatchListAdapter adapter;

    private String mRid, mType, mBatchNumber, mRetainDecimal, mMatId, mSupplierCode;

    private ItemListBean mMaterielDetail;


    private CYChangeStorageGetBatchRequestBean batchRequestBean;

    private boolean mFlag;
    private String location_id_output;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_out_storage_picking_detail);
        initView(OutStorageDetailBatchActivity.this);
    }

    @Override
    protected void onResumeImpl() {
        initData(OutStorageDetailBatchActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        pickingOutStorageDetailList = (PullableListView) activity.findViewById(R.id.pickingOutStorageDetailList);
        refresh = (PullToRefreshLayout) activity.findViewById(R.id.pickingOutStorageDetailRefresh);
    }

    private void initData(Activity activity) {
        title.setText(getResources().getString(R.string.activity_out_storage_picking_detail_acquisition_of_subsidiary));
        ActivityUtils.initBackAndFunction(activity, "概览", new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String message = check(activity);
                if (message != null) {
                    DialogUtils.getConfirmDialog(OutStorageDetailBatchActivity.this, message, new DialogUtils.ConfirmDialogListener() {
                        @Override
                        public void onConfirm(Dialog dialog) {
                            OutStorageDetailBatchActivity.this.finish();
                        }
                    }).show();
                } else {
                    updateInfo(OutStorageDetailBatchActivity.this);
                    OutStorageDetailBatchActivity.this.finish();
                }
            }
        });

        ActivityUtils.initRightFunction(activity, ActivityUtils.getRightViewWithName(activity, "全部批次"), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                getBatch(activity, "");
            }
        });

        pickingOutStorageDetailList.setPullUpFlag(false);
        pickingOutStorageDetailList.setPullDownFlag(false);
        mBatchNumber = "";
        getExtra(activity);
        getData(activity);
        setmScanListener((String scanResult, int length) -> {
            String type = QRCodeUtils.getQRCodeType(scanResult);
            switch (type) {
                case QRCodeConstant.CY_TYPE_BATCH:
                    mBatchNumber = scanResult;
                    getBatch(activity, mBatchNumber);
                    break;
            }
        }, QRCodeConstant.CY_TYPE_BATCH);
    }

    private void getExtra(Activity activity) {
        mRid = activity.getIntent().getStringExtra(OutStorageExtra.SERIAL);
        mType = activity.getIntent().getStringExtra(OutStorageExtra.TYPE);
        mMatId = activity.getIntent().getStringExtra(ChangeStorageExtra.MAT_ID);
        mSupplierCode = activity.getIntent().getStringExtra(ChangeStorageExtra.SUPPLIER_CODE);
        location_id_output = getIntent().getStringExtra(AllocationOutStorageExtra.ALLOCATION_LOCATION_ID_OUTPUT);
    }

    //填充数据
    private void addOutStorageBatchItemListData(Context context, ItemListBean materielDetail, List<BatchBean.BatchInfoBean> batchList, String batchNumber, ListView listView) {

        adapter = new OutStorageDetailBatchListAdapter(context, materielDetail, batchList, batchNumber, mType, new OutStorageDetailBatchListener() {
            @Override
            public void onGetBatch(String batchNumber) {
                mBatchNumber = batchNumber;
                getBatch(context, batchNumber);
            }

            @Override
            public void onDeleteBatchItem(BatchBean.BatchInfoBean batchInfoBean) {
                deleteBatchItem(context, batchInfoBean);
            }
        });
        listView.setAdapter(adapter);
    }

    //删除批次项
    private void deleteBatchItem(Context context, BatchBean.BatchInfoBean pickingOutStorageItem) {
        List<BatchBean.BatchInfoBean> mBatchList = mMaterielDetail.getBatchList();
        if (mBatchList != null && !mBatchList.isEmpty()) {
            for (int i = 0; i < mBatchList.size(); i++) {
                BatchBean.BatchInfoBean batchItem = mBatchList.get(i);
//                if (batchItem.getPosition_code().equals(pickingOutStorageItem.getPosition_code()) && batchItem.getBatch().equals(pickingOutStorageItem.getBatch())) {
                if (batchItem.getStock_id().equals(pickingOutStorageItem.getStock_id())) {
                    mBatchList.remove(batchItem);
                    break;
                }
            }
            mMaterielDetail.setBatchList(mBatchList);
        }
        addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
    }

    //获取单个批次和全部批次,batchNumber==""时获取全部批次
    private void getBatch(Context context, String batchNumber) {
        Log.i("bbbb", String.valueOf(mType) + "xxxx");
        switch (mType) {
            case OutStorageUtils.OUT_STORAGE_TYPE_PICKING:
                //领料出库
                AddBatchRequest.request(context, batchNumber, mMaterielDetail.getMat_id(), mMaterielDetail.getFty_id(), mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_PICKING, new GsonBeanListener<BatchBean>() {
                    @Override
                    public void onSuccess(BatchBean bean) {
                        if (TextUtils.isEmpty(batchNumber)) {
                            mFlag = OutStorageUtils.FLAG_FLUSH;
                        } else {
                            if (mFlag == OutStorageUtils.FLAG_FLUSH) {
                                mMaterielDetail.setBatchList(new ArrayList<>());
                            }
                            mFlag = OutStorageUtils.FLAG_ADD;
                        }
                        List<BatchBean.BatchInfoBean> realBatchList = OutStorageUtils.filterBatch(mMaterielDetail.getBatchList(), bean.getBody());
                        int size = realBatchList.size();
                        if (size > 0) {
                            List<BatchBean.BatchInfoBean> resultBatchList = mMaterielDetail.getBatchList();
                            resultBatchList.addAll(realBatchList);
                            mMaterielDetail.setBatchList(resultBatchList);
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        } else {
                            Utils.middleToast(context, context.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_has_been_added_or_undetected));
                        }
                    }
                });
                break;

            case OutStorageUtils.OUT_STORAGE_TYPE_SALE:
                //销售出库
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_PRODUCTION:
                //生产领用
                AddBatchRequest.request(context, batchNumber, mMaterielDetail.getMat_id(), mMaterielDetail.getFty_id(), mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_PRODUCTION, new GsonBeanListener<BatchBean>() {
                    @Override
                    public void onSuccess(BatchBean bean) {
                        if (TextUtils.isEmpty(batchNumber)) {
                            mFlag = OutStorageUtils.FLAG_FLUSH;
                        } else {
                            if (mFlag == OutStorageUtils.FLAG_FLUSH) {
                                mMaterielDetail.setBatchList(new ArrayList<>());
                            }
                            mFlag = OutStorageUtils.FLAG_ADD;
                        }
                        List<BatchBean.BatchInfoBean> realBatchList = OutStorageUtils.filterBatch(mMaterielDetail.getBatchList(), bean.getBody());
                        int size = realBatchList.size();
                        if (size > 0) {
                            List<BatchBean.BatchInfoBean> resultBatchList = mMaterielDetail.getBatchList();
                            resultBatchList.addAll(realBatchList);
                            mMaterielDetail.setBatchList(resultBatchList);
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        } else {
                            Utils.middleToast(context, context.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_has_been_added_or_undetected));
                        }
                    }
                });
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_ALLOCATION:
                //調撥出庫
//                AddBatchRequest.request(context, batchNumber, mMaterielDetail.getMat_id(), mMaterielDetail.getFty_id(), mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_ALLOCATING, new GsonBeanListener<BatchBean>() {
//                    @Override
//                    public void onSuccess(BatchBean bean) {
//                        List<BatchBean.BatchInfoBean> realBatchList = OutStorageUtils.filterBatch(mMaterielDetail.getBatchList(), bean.getBody());
//                        int size = realBatchList.size();
//                        if (size > 0) {
//                            List<BatchBean.BatchInfoBean> resultBatchList = mMaterielDetail.getBatchList();
//                            resultBatchList.addAll(realBatchList);
//                            mMaterielDetail.setBatchList(resultBatchList);
//                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
//                        } else {
//                            Utils.middleToast(context, context.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_has_been_added_or_undetected));
//                        }
//                    }
//                });
                AllocationAllBatchRequest.request(context, mMaterielDetail.getMat_id(), location_id_output, batchNumber, new GsonBeanListener<BatchBean>() {
                    @Override
                    public void onSuccess(BatchBean bean) {
                        List<BatchBean.BatchInfoBean> realBatchList = OutStorageUtils.filterBatch(mMaterielDetail.getBatchList(), bean.getBody());
                        int size = realBatchList.size();
                        if (size > 0) {
                            List<BatchBean.BatchInfoBean> resultBatchList = mMaterielDetail.getBatchList();
                            resultBatchList.addAll(realBatchList);
                            mMaterielDetail.setBatchList(resultBatchList);
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        } else {
                            Utils.middleToast(context, context.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_has_been_added_or_undetected));
                        }
                    }
                });
                break;
            case CYChangeStorageUtils.CHANGE_STORAGE_TYPE:
                batchRequestBean = CYChangeStorageUtils.getBatchRequestBean(context, mMatId, batchNumber);
                CYChangeStorageMaterialBatchRequest.request(context, batchRequestBean, new GsonBeanListener<BatchBean>() {
                    @Override
                    public void onSuccess(BatchBean bean) {
                        if (TextUtils.isEmpty(batchNumber)) {
                            mFlag = OutStorageUtils.FLAG_FLUSH;
                        } else {
                            if (mFlag == OutStorageUtils.FLAG_FLUSH) {
                                mMaterielDetail.setBatchList(new ArrayList<>());
                            }
                            mFlag = OutStorageUtils.FLAG_ADD;
                        }
                        List<BatchBean.BatchInfoBean> realBatchList = OutStorageUtils.filterBatch(mMaterielDetail.getBatchList() == null ? new ArrayList<>() : mMaterielDetail.getBatchList(), bean.getBody());
                        int size = realBatchList.size();
                        if (size > 0) {
                            List<BatchBean.BatchInfoBean> resultBatchList = mMaterielDetail.getBatchList() == null ? new ArrayList<>() : mMaterielDetail.getBatchList();
                            resultBatchList.addAll(realBatchList);
                            mMaterielDetail.setBatchList(resultBatchList);
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        } else {
                            Utils.middleToast(context, context.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_has_been_added_or_undetected));
                        }
                    }
                });
                break;
        }
    }

    //获取默认数据，可能是默认批次或者其他
    private void getData(Context context) {
        List<BatchBean.BatchInfoBean> checkBatchList;
        switch (mType) {
            case OutStorageUtils.OUT_STORAGE_TYPE_PICKING:
                //领料出库
                mMaterielDetail = OutStorageUtils.getPickingOutStorageDetailBySerial(context, mRid);
                checkBatchList = mMaterielDetail.getBatchList();
                if (checkBatchList == null || checkBatchList.isEmpty()) {
                    GetDefaultBatchRequest.request(context, mMaterielDetail.getMat_id(), mMaterielDetail.getOutput_qty(), mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_PICKING, new GsonBeanListener<BatchBean>() {
                        @Override
                        public void onSuccess(BatchBean bean) {
                            mMaterielDetail.setBatchList(bean.getBody());
                            mRetainDecimal = mMaterielDetail.getDecimal_place();
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        }
                    });
                } else {
                    mRetainDecimal = mMaterielDetail.getDecimal_place();
                    addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                }
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_SALE:
                //销售出库
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_PRODUCTION:
                //生产领用
                mMaterielDetail = OutStorageUtils.getProductionOutStorageDetailBySerial(context, mRid);
                checkBatchList = mMaterielDetail.getBatchList();
                if (checkBatchList == null || checkBatchList.isEmpty()) {
                    GetDefaultBatchRequest.request(context, mMaterielDetail.getMat_id(), mMaterielDetail.getOutput_qty(), mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_PRODUCTION, new GsonBeanListener<BatchBean>() {
                        @Override
                        public void onSuccess(BatchBean bean) {
                            mMaterielDetail.setBatchList(bean.getBody());
                            mRetainDecimal = mMaterielDetail.getDecimal_place();
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        }
                    });
                } else {
                    mRetainDecimal = mMaterielDetail.getDecimal_place();
                    addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                }
                break;
            case CYChangeStorageUtils.CHANGE_STORAGE_TYPE:
                mMaterielDetail = CYChangeStorageUtils.getMaterialDetailById(context, mMatId, mSupplierCode, false);
                checkBatchList = mMaterielDetail.getBatchList() == null ? new ArrayList<>() : mMaterielDetail.getBatchList();
                mRetainDecimal = mMaterielDetail.getDecimal_place();
                addOutStorageBatchItemListData(context, mMaterielDetail, checkBatchList, mBatchNumber, pickingOutStorageDetailList);
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_ALLOCATION:
                //调拨出库
                int type = getIntent().getIntExtra(AllocationOutStorageExtra.TYPE, 0);
                switch (type) {
                    case 0:
                        mMaterielDetail = OutStorageUtils.getAllocationOutStorageDetailBySerial(context, mRid);
                        break;
                    case 1:
                        mMaterielDetail = OutStorageUtils.getAllocationOutStorageDetailByMatid(context, mRid);
                        break;
                }
                checkBatchList = mMaterielDetail.getBatchList();
                if (checkBatchList == null || checkBatchList.isEmpty()) {
//                    GetDefaultBatchRequest.request(context, mMaterielDetail.getMat_id(), mMaterielDetail.getOutput_qty(), mMaterielDetail.getLocation_id(), null, TypeEnum.OUT_STORAGE_ALLOCATING, new GsonBeanListener<BatchBean>() {
//                        @Override
//                        public void onSuccess(BatchBean bean) {
//                            mMaterielDetail.setBatchList(bean.getBody());
//                            mRetainDecimal = mMaterielDetail.getDecimal_place();
//                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
//                        }
//                    });
                    //获取全部批次
                    AllocationAllBatchRequest.request(context, mMaterielDetail.getMat_id(), location_id_output, null, new GsonBeanListener<BatchBean>() {
                        @Override
                        public void onSuccess(BatchBean bean) {
                            mMaterielDetail.setBatchList(bean.getBody());
                            mRetainDecimal = mMaterielDetail.getDecimal_place();
                            addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                        }
                    });
                } else {
                    mRetainDecimal = mMaterielDetail.getDecimal_place();
                    addOutStorageBatchItemListData(context, mMaterielDetail, mMaterielDetail.getBatchList(), mBatchNumber, pickingOutStorageDetailList);
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        String message = check(OutStorageDetailBatchActivity.this);
        if (message != null) {
            DialogUtils.getConfirmDialog(OutStorageDetailBatchActivity.this, message, new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    OutStorageDetailBatchActivity.super.onBackPressed();
                }
            }).show();
        } else {
            updateInfo(OutStorageDetailBatchActivity.this);
            OutStorageDetailBatchActivity.super.onBackPressed();
        }
    }


    private void updateInfo(Context context) {
        switch (mType) {
            case OutStorageUtils.OUT_STORAGE_TYPE_PICKING:
                //领料出库
                mMaterielDetail.setBatchList(OutStorageUtils.removeNoNumberItem(adapter.getmBatchList()));
                mMaterielDetail.setActualSendNumber(adapter.getmActualSendNumber());
                OutStorageUtils.updatePickingOutStorageDetail(context, mMaterielDetail);
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_SALE:
                //销售出库
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_PRODUCTION:
                //生产领用
                mMaterielDetail.setBatchList(OutStorageUtils.removeNoNumberItem(adapter.getmBatchList()));
                mMaterielDetail.setActualSendNumber(adapter.getmActualSendNumber());
                OutStorageUtils.updateProductionOutStorageDetail(context, mMaterielDetail);
                break;
            case CYChangeStorageUtils.CHANGE_STORAGE_TYPE:
                mMaterielDetail.setBatchList(OutStorageUtils.removeNoNumberItem(adapter.getmBatchList()));
                mMaterielDetail.setActualSendNumber(adapter.getmActualSendNumber());
                CYChangeStorageUtils.updateProductionOutStorageDetail(context, mMaterielDetail);
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_ALLOCATION:
                //调拨出庫
                mMaterielDetail.setBatchList(OutStorageUtils.removeNoNumberItem(adapter.getmBatchList()));
                mMaterielDetail.setActualSendNumber(adapter.getmActualSendNumber());
                OutStorageUtils.updateAllocatingOutStorageDetail(context, mMaterielDetail);
                break;
        }
    }

    private String check(Context context) {
        String message;
        List<BatchBean.BatchInfoBean> currentBatchList = adapter.getmBatchList();

        switch (mType) {
            case CYChangeStorageUtils.CHANGE_STORAGE_TYPE:
                message = OutStorageUtils.checkNumber(context, currentBatchList);
                if (message != null) {
                    return message;
                }
                message = OutStorageUtils.checkRetainDecimal(context, currentBatchList, mRetainDecimal);
                if (message != null) {
                    return message;
                }
                message = OutStorageUtils.checkCanSendNumber(context, adapter.getmActualSendNumber(), mMaterielDetail.getOrder_qty());
                if (message != null) {
                    return message;
                }
                break;
            case OutStorageUtils.OUT_STORAGE_TYPE_ALLOCATION:
                message = OutStorageUtils.checkNumber(context, currentBatchList);
                if (message != null) {
                    return message;
                }
                message = OutStorageUtils.checkRetainDecimal(context, currentBatchList, mRetainDecimal);
                if (message != null) {
                    return message;
                }
                break;
            default:
                message = OutStorageUtils.checkNumber(context, currentBatchList);
                if (message != null) {
                    return message;
                }
                message = OutStorageUtils.checkRetainDecimal(context, currentBatchList, mRetainDecimal);
                if (message != null) {
                    return message;
                }
                message = OutStorageUtils.checkCanSendNumber(context, adapter.getmActualSendNumber(), ArithUtils.sub(mMaterielDetail.getOrder_qty(), mMaterielDetail.getSend_qty()).toString());
                if (message != null) {
                    return message;
                }
                break;
        }

        return message;
    }


}
